package edu.clarkson.ee368.spring2012.coreservices;

import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;

@Stateless
public class NotificationServiceBean implements NotificationService {
	
	@Inject
	@AndroidC2DM
	private DeviceNotifier deviceNotifier;
	
	@Inject
	@ClientLogin
	private GoogleServiceAuthenticator authenticator;

	@EJB
	private ApplicationService appService;
	
	@EJB
	private AccountDAO accountDAO;

	@Override
	public void sendMessage(String applicationSecret, String targetUserName,
			Map<String, String> data) throws AuthenticationOutOfDateException {
		HostedApplication application = appService.getApplication(applicationSecret);
		Account user = accountDAO.getAccountFromUser(targetUserName);
		Device device = user.getDevice();
		try {
			deviceNotifier.sendMessage(application, device, data);
		} catch (GoogleServiceAuthenticationException e) {
			throw new AuthenticationOutOfDateException();
		}
	}

	@Override
	public void authenticate(String applicationSecret, String ownerEmail,
			String ownerPassword) {
		HostedApplication application = appService.getApplication(applicationSecret);
		authenticator.authenticate(application, ownerEmail, ownerPassword);
		appService.updateApplication(application);
	}	
}
